package edu.cque.sp06zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import edu.cque.sp01.web.util.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Hua
 * @create 2022-08-19 0:07
 */
@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器类型: pre, routing, post, error
    @Override
    public String filterType() {
        //return "pre"; //一样的
        return FilterConstants.PRE_TYPE;
    }

    //设置过滤器 顺序号
    @Override
    public int filterOrder() {
        //前置过滤器中有5个默认过滤器, 自定义过滤器放到末尾
        return 6;
    }

    //判断针对当前请求是否要执行下面的 过滤代码  //.. 如果返回false,不指令下面的过滤代码,那又会执行哪里呢???
    @Override
    public boolean shouldFilter() {
        /*
        调用商品,需要判断权限
        调用用户或者订单不检查权限
         */
        //1. 获得一个请求上下文对象
        // TODO: 2022/8/19  //断点看过滤器
        RequestContext context = RequestContext.getCurrentContext();
        //2. 从上下文对象获取调用的后台服务的 serviceId
        String serviceId = (String) context.get(FilterConstants.SERVICE_ID_KEY);
        //3. 如果调用的是item-service,返回true
        return "item-service".equals(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //获取请求头token
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            //阻止继续调用
            context.setSendZuulResponse(false);
            //直接返回
            //JsonResult - {code:400,msg:未登录,data:null}
            String json = JsonResult.build().code(400).msg("not login").toString();
            context.addZuulResponseHeader("Content-Type",
                    "application/json;charset=UTF-8");
            context.setResponseBody(json);

        }
        return null;//zuul 当前版本的返回值没有作用
    }
}
